import { constantRouterMap } from '@/router'
const _import = require('@/router/_import_' + process.env.NODE_ENV)
const _import_router = require('@/router/_import_addRouter')

function filterAsyncRouter(menusLs) {
  const filterList = getMenusPathList(menusLs)

  let addrouters = []
  config.ROUTERPATHS.forEach(path => {
    const routers = _import_router(path)
    addrouters = addrouters.concat(routers)
  })

  const newRouter = filterRouters(addrouters, filterList)
  return newRouter
}

/**
 * 通过递归的方式将用户没有权限的路由给去掉
 * @param  menus
 */
function filterRouters(routers, filterList) {
  const newRouter = []
  routers.forEach(element => {
    const path = element.path
    if (filterList[path] || (element.children && element.children.length > 0) || element.path === '*') {
      const tmp = element
      if (tmp.children) {
        tmp.children = filterRouters(tmp.children, filterList)
      }
      if (filterList[path]) {
        const menu = filterList[path]
        const meta = {
          icon: menu.icon,
          name: menu.menuId,
          title: menu.menuName
        }
        tmp.meta = meta
      }
      try {
        if (tmp.component) {
          tmp.component = _import(tmp.component)
        } else {
          tmp.component = _import('platform/errorPage/404')
        }
      } catch (error) {
        tmp.component = _import('platform/errorPage/404')
      }

      newRouter.push(tmp)
    }
  })
  return newRouter
}

function getCommonOperation(menus) {
  const commonOperation = []
  menus.forEach(element => {
    if (element.menuId === 'CommonOperations') {
      if (element.children) {
        element.children.forEach(m => {
          commonOperation.push(m.menuId)
        })
      }
      return false
    }
  })
  return commonOperation
}

function getMenusPathList(menus) {
  let pathList = {}
  menus.forEach(element => {
    if (element.url) {
      pathList[element.url] = element
    }
    if (element.children) {
      pathList = Object.assign(pathList, getMenusPathList(element.children))
    }
  })
  return pathList
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menus } = data
        const accessedRouters = filterAsyncRouter(menus)
        commit('SET_ROUTERS', accessedRouters)
        const commonOperation = getCommonOperation(menus)
        resolve(commonOperation)
      })
    }
  }
}

export default permission
